#!/usr/bin/env python
#coding=utf-8

import json
import logging
import datetime
import pandas as pd
from pprint import pprint
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkecs.request.v20140526.AddTagsRequest import AddTagsRequest
from aliyunsdkecs.request.v20140526.DescribeRenewalPriceRequest import DescribeRenewalPriceRequest
from core.logger import logger
from common.aliyun.aliyun_client import AliYunClient
from common.aliyun.aliyun_common import AliYunCommon
from common.utils import CommonTimeUtils

class AliYunHost(object):
    def __init__(self):
        self.aliyun_client = AliYunClient()
        self.aliyun = self.aliyun_client.get_all_client()
        self.aliyun_common = AliYunCommon()



    def get_host_info(self, account):
        page_size = 100
        page_number = 1
        hosts_info = []
        while True:
            request = DescribeInstancesRequest()
            request.set_accept_format('json')

            request.set_PageNumber(page_number)
            request.set_PageSize(page_size)

            try:
                response = account["client"].do_action_with_exception(request)
                response = json.loads(str(response, encoding='utf-8'))

                for host in response["Instances"]["Instance"]:
                    host_ip = host["NetworkInterfaces"]["NetworkInterface"][0]["PrimaryIpAddress"]
                    tag = self.aliyun_common.get_tag(host)
                    
                    # 获取主机价格
                    result, instance_price = self.get_instance_price(account["name"], host)
                    if not result:
                        logger.error(f"get host:{host_ip} price failed")
                        instance_price = -1
                        
                    create_time = datetime.datetime.strptime(host['CreationTime'], "%Y-%m-%dT%H:%MZ")
                    
                    host_info = {
                        "instance_id": host["InstanceId"],
                        "name": host["InstanceName"],
                        "ip": host_ip,
                        "cpu": host["Cpu"],
                        "mem": int(host['Memory']/1024),
                        "tag": tag,
                        "instance_charge_type": host["InstanceChargeType"],
                        "instance_price": instance_price,
                        "status": host["Status"],
                        "cloud_platform": "aliyun",
                        "account_name": account["name"],
                        "create_time": create_time
                    }

                    hosts_info.append(host_info)

                if page_number * page_size >= response["TotalCount"]:
                    break
                else:
                    page_number += 1

            except Exception as e:
                logger.error("get aliyun_hosts_info error =>{}".format(e))
                return None

        return hosts_info



    def get_all_hosts_info(self):
        hosts_info = []
        for account in self.aliyun:
            host_info = self.get_host_info(account)
            if not host_info:
                logger.error(f"{account['name']} => get host info failed")
                return None
            hosts_info.extend(host_info)
        logger.info("get all hosts_info success")
        return hosts_info



    def get_instance_price(self, account_name, host):
        try:
            if host["InstanceChargeType"] == "PostPaid":
                # 按量付费
                return True, 0
                        
            account = self.aliyun_client.get_one_client(account_name)
            if not account:
                logger.error(f"get client:{account_name} failed")
                return False, None

            request = DescribeRenewalPriceRequest()
            request.set_accept_format('json')

            request.set_ResourceId(host["InstanceId"])

            response = account['client'].do_action_with_exception(request)
            response = json.loads(str(response, encoding='utf-8'))
            instance_price = response["PriceInfo"]["Price"]["TradePrice"]
        except Exception as e:
            logger.error(f"account:{account_name} resource_id:{host['InstanceId']}, get price error=>{e}")
            return False, None

        return True, instance_price



def main():
    aliyun_host = AliYunHost()
    aliyun_host.get_all_hosts_info()
    print("hello")

    return True



if __name__ == "__main__":
    main()
